<template>
  <view class="success-wrap">
    <view class="top-card">
      <view class="icon">✓</view>
      <view class="title">充值成功</view>
      <view class="sub" v-if="amountText">本次充值金额：<text class="hl">{{ amountText }}</text></view>
    </view>

    <view class="recommend-card">
      <view class="rec-title">为你推荐好评率高的医生</view>
      <view v-if="loading" class="loading">加载推荐中...</view>
      <view v-else>
        <view v-if="recommends.length === 0" class="empty">暂无推荐</view>
        <view v-else class="doctor-list">
          <view class="doctor-item" v-for="doc in recommends" :key="doc.id">
            <image class="avatar" :src="doc.avatar" mode="aspectFill" @click="toDoctorDetail(doc)" />
            <view class="info" @click="toDoctorDetail(doc)">
              <view class="name-row">
                <text class="name">{{ doc.name }}</text>
                <text class="title-text" v-if="doc.title">{{ doc.title }}</text>
              </view>
              <view class="hospital" v-if="doc.hospital">{{ doc.hospital }}</view>
              <view class="meta">
                <text class="rate">好评率 {{ formatPercent(doc.praiseRate) }}</text>
                <text class="dot">·</text>
                <text class="price" v-if="doc.price">{{ doc.price }}币/次</text>
              </view>
            </view>
            <button class="reserve" @click="toDoctorDetail(doc)">预约</button>
          </view>
        </view>
      </view>
    </view>

    <view class="bottom-actions">
      <button class="primary" @click="goRecords">立即查看</button>
    </view>
  </view>
</template>

<script>
import { getDepartmentList } from '@/api/department.js'
import { getDoctorsByDeptId } from '@/api/doctor.js'
import config from '@/config.js'

export default {
  name: 'RechargeSuccess',
  data() {
    return {
      amount: null,
      channel: null,
      loading: false,
      recommends: []
    }
  },
  onLoad(query) {
    const a = Number(query?.amount)
    this.amount = Number.isFinite(a) && a > 0 ? a : null
    const ch = Number(query?.channel)
    this.channel = Number.isFinite(ch) ? ch : null
    this.fetchRecommendations()
  },
  computed: {
    amountText() {
      if (this.amount == null) return ''
      try {
        return `¥${Number(this.amount).toFixed(2)}`
      } catch {
        return `${this.amount}`
      }
    }
  },
  methods: {
    async fetchRecommendations() {
      this.loading = true
      try {
        const depRes = await getDepartmentList()
        const list = Array.isArray(depRes?.data) ? depRes.data : (Array.isArray(depRes) ? depRes : [])
        const ids = (list || []).slice(0, 3).map(d => d.id || d.deptId || d.departmentId).filter(Boolean)
        if (ids.length === 0) {
          this.recommends = []
          return
        }
        const tasks = ids.map(id => (
          getDoctorsByDeptId(id).then(res => Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])).catch(() => [])
        ))
        const chunks = await Promise.all(tasks)
        const merged = [].concat(...chunks)
        const normalized = merged.map(this.normalizeDoctor)
        const sorted = normalized
          .filter(d => d && d.id)
          .sort((a, b) => (this.numPercent(b.praiseRate) - this.numPercent(a.praiseRate)))
          .slice(0, 5)
        this.recommends = sorted
      } catch (e) {
        console.error('获取推荐医生失败', e)
        this.recommends = []
      } finally {
        this.loading = false
      }
    },
    toDoctorDetail(doc) {
      if (!doc || !doc.id) return
      uni.navigateTo({ url: `/pages/doctors/detail?doctorId=${doc.id}` })
    },
    goRecords() {
      uni.navigateTo({ url: '/pages/wallet/recharge' })
    },
    normalizeDoctor(d) {
      if (!d) return {}
      const ratingNum = parseFloat(
        d.praiseRate !== undefined ? d.praiseRate : (d.praise_rate !== undefined ? d.praise_rate : d.rating)
      )
      const priceNum = parseFloat(d.consultFee || d.price || d.consultPrice)
      const rawAvatar = d.doctorImage || d.avatar || d.headImg || d.avatarUrl
      return {
        id: d.id || d.doctorId || d.userId,
        name: d.doctorName || d.name || d.realName || '医生',
        title: d.roleName || d.title || d.jobTitle || '',
        hospital: d.hospitalName || d.hospital || '',
        avatar: this.normalizeUrl(rawAvatar) || '/static/images/profile.jpg',
        praiseRate: isNaN(ratingNum) ? '' : ratingNum,
        price: isNaN(priceNum) ? '' : priceNum
      }
    },
    numPercent(v) {
      if (v === null || v === undefined || v === '') return 0
      let n = Number(v)
      if (!Number.isFinite(n)) {
        const s = String(v).trim()
        if (s.endsWith('%')) n = parseFloat(s.slice(0, -1))
      }
      if (!Number.isFinite(n)) return 0
      return n > 0 && n <= 1 ? n * 100 : n
    },
    formatPercent(v) {
      if (v === null || v === undefined || v === '') return '0%'
      let str = String(v).trim()
      if (str.endsWith('%')) {
        const n = parseFloat(str.slice(0, -1))
        if (isNaN(n)) return '0%'
        const clamped = Math.max(0, Math.min(n, 100))
        return Math.round(clamped) + '%'
      }
      const num = parseFloat(str)
      if (isNaN(num)) return '0%'
      let percent = (num > 0 && num <= 1) ? num * 100 : num
      percent = Math.max(0, Math.min(percent, 100))
      return Math.round(percent) + '%'
    },
    normalizeUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) return url
      if (url.startsWith('/')) return `${config.baseUrl}${url}`
      return url
    }
  }
}
</script>

<style lang="scss" scoped>
.success-wrap {
  min-height: 100vh;
  background: #f5f6f7;
  /* 顶部安全区，避免与系统导航产生缝隙导致细线 */
  padding-top: env(safe-area-inset-top, 0);
  padding-bottom: env(safe-area-inset-bottom, 0);
  /* 隐藏可能出现的亚像素缝隙发绿线 */
  overflow: hidden;
}
.top-card {
  margin: 24rpx; padding: 40rpx 24rpx; background: #fff; border-radius: 20rpx; text-align: center;
  box-shadow: 0 6rpx 18rpx rgba(0,0,0,0.04);
}
.icon { width: 100rpx; height: 100rpx; line-height: 100rpx; margin: 0 auto 12rpx; border-radius: 50%; background: #e8f3ff; color: #2a7cff; font-size: 56rpx; font-weight: 700; }
.title { font-size: 34rpx; color: #333; font-weight: 700; margin-bottom: 8rpx; }
.sub { font-size: 26rpx; color: #666; }
.sub .hl { color: #2a7cff; font-weight: 600; }

.recommend-card { margin: 0 24rpx; background: #fff; border-radius: 20rpx; padding: 20rpx; }
.rec-title { font-size: 30rpx; color: #333; font-weight: 600; margin-bottom: 8rpx; }
.loading, .empty { padding: 24rpx 0; color: #999; text-align: center; font-size: 26rpx; }
.doctor-list { display: flex; flex-direction: column; }
.doctor-item { display: flex; align-items: center; padding: 20rpx 0; border-bottom: 1px solid #f0f2f5; }
.doctor-item:last-child { border-bottom: 0; }
.avatar { width: 120rpx; height: 120rpx; border-radius: 60rpx; margin-right: 16rpx; }
.info { flex: 1; min-width: 0; }
.name-row { display: flex; align-items: center; gap: 10rpx; }
.name { font-size: 30rpx; color: #333; font-weight: 600; }
.title-text { font-size: 24rpx; color: #667eea; }
.hospital { margin-top: 4rpx; font-size: 24rpx; color: #666; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.meta { margin-top: 6rpx; display: flex; gap: 10rpx; align-items: center; font-size: 24rpx; color: #888; }
.meta .rate { color: #666; }
.meta .price { color: #2a7cff; }
.meta .dot { color: #bbb; }
.reserve { flex-shrink: 0; background: #2a7cff; color: #fff; border-radius: 12rpx; height: 60rpx; line-height: 60rpx; padding: 0 24rpx; font-size: 26rpx; }

.bottom-actions { position: sticky; bottom: 0; padding: 16rpx 24rpx env(safe-area-inset-bottom, 16rpx); background: #f5f6f7; }
.primary { width: 100%; height: 84rpx; line-height: 84rpx; border-radius: 12rpx; background: #2a7cff; color: #fff; font-size: 32rpx; }
</style>
